package info.batcloud.fanli.api.security.authentication;

import info.batcloud.fanli.api.security.handler.LoginAuthenticationSuccessHandler;
import info.batcloud.fanli.core.domain.DefaultUserDetails;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.security.authentication.NoopAuthenticationManager;
import info.batcloud.fanli.core.service.UserService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RefreshAuthenticationAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    @Inject
    private UserService userService;

    @Inject
    private LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    public RefreshAuthenticationAuthenticationProcessingFilter() {
        super("/login/refresh");
        setAuthenticationManager(new NoopAuthenticationManager());
        setAuthenticationDetailsSource(authenticationDetailsSource);
    }

    @PostConstruct
    public void afterPropertiesSet() {
        this.setAuthenticationSuccessHandler(loginAuthenticationSuccessHandler);
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {

        DefaultUserDetails userDetails = userService.loadUserByUserId(SecurityHelper.loginUserId());
        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }


}
